<script setup lang="ts">
import { getCaptchaImage, login } from "@/api/admin/login";
import {
  ElForm,
  ElFormItem,
  ElInput,
  ElSpace,
  ElButton,
  ElCheckbox,
  ElLink,
  ElMessage,
} from "element-plus";
import { onMounted, reactive, ref } from "vue";
import { useUserStore } from "@/store/modules/user";
import { useRouter } from "vue-router";
const { push } = useRouter();
const userStore = useUserStore();
const {
  setAccessToken,
  setRefreshToken,
  setUserInfo,
  setTokenKey,
  setLoginInfo,
  setUserRoles,
} = userStore;
const emit = defineEmits(["changeForm"]);
const formData = reactive({
  username: "admin",
  password: "admin",
  rememberMe: false,
  code: "",
  uuid: "",
});
const loginRef = ref();

const captchaImage = ref("");

// 获取验证码
const getCaptchaImageClick = async ()=>{
  // console.log("获取验证码");
 const res = await getCaptchaImage();
 captchaImage.value = res.data.data;
 formData.uuid = res.data.uuid;
//  console.log(res);
}

onMounted(() => {
  getCaptchaImageClick();
});

// 登录
const onLogin = async () => {
  await loginRef.value.validate();

  const { username, password, rememberMe, code, uuid } = formData;

  const ret = await login({ username, password, code, uuid });
  if (ret.code === 200) {
    // console.log(ret);

    const { userInfo, tokenKey } = ret.data;
    const access_token = "bearer" + " " + ret.data.access_token;
    const refresh_token = "bearer" + " " + ret.data.refresh_token;

    
    if(userInfo.roles.length === 0){
      ElMessage.error("当前用户没有角色，请先联系管理员分配角色");
      return
    }
    // 是否记住账号密码
    if (rememberMe) {
      setLoginInfo({ username, password });
    } else {
      setLoginInfo(undefined);
    }
    setAccessToken(access_token);
    setRefreshToken(refresh_token);
    // console.log(userInfo)
    delete userInfo.permission;
    setUserInfo(userInfo);
    // console.log(permission)
    setUserRoles(userInfo.roles);
    setTokenKey(tokenKey);


    ElMessage.success("登录成功");
    push("/");

  } else {
    ElMessage.error(ret.msg);
    console.error(ret);
  }
};

// 切换表单
const changeForm = () => {
  emit("changeForm");
};
</script>

<template>
  <ElForm :model="formData" label-position="left" class="login-form" ref="loginRef" label-width="auto">
    <h3 style="text-align: center" class="title">{{ $t("login.login") }}</h3>
    <ElFormItem prop="username" :label="$t('login.username')" :rules="[{ required: true, message: '请输入用户名' }]" >
      <ElInput
        :placeholder="$t('login.usernamePlaceholder')"
        v-model="formData.username"
      />
    </ElFormItem>
    <ElFormItem prop="password" :label="$t('login.password')" :rules="[{ required: true, message: '请输入密码' }]" >
      <ElInput
        :placeholder="$t('login.passwordPlaceholder')"
        v-model="formData.password"
      />
    </ElFormItem>
    
      <ElFormItem prop="code" label="验证码" :rules="[{ required: true, message: '请输入验证码' }]" >
        <div style="display: flex;">
        <ElInput
        class="captchaInput"
          placeholder="请输入验证码"
          v-model="formData.code"
        />
        <div class="captchaImage" @click="getCaptchaImageClick" v-html="captchaImage"></div>
      </div>
      </ElFormItem>

    <ElSpace :size="10" style="width: 100%" :fill="true" direction="horizontal">
      <ElSpace style="display: flex; justify-content: space-between">
        <ElCheckbox v-model="formData.rememberMe">{{
          $t("login.rememberMe")
        }}</ElCheckbox>
        <ElLink :underline="false" type="primary">{{
          $t("login.forgetPassword")
        }}</ElLink>
      </ElSpace>
      <ElButton type="primary" @click="onLogin">{{ $t("login.login") }}</ElButton>
      <ElButton @click="changeForm">{{ $t("login.register") }}</ElButton>
    </ElSpace>
  </ElForm>
</template>

<style lang="less" scoped>

.login-form{
  .title{
    margin-bottom: 20px;
  }
}




.captchaImage {
  width: 150px;
  cursor: pointer;
  border: 1px solid #ccc;
}
</style>
